package com.kotlin.android.ktx.ext

import android.content.Context
import android.content.res.Resources
import android.util.TypedValue
import android.view.View
import java.util.*

/**
 *
 * Created on 2020/6/5.
 *
 * @author o.s
 */

/**
 * 屏幕宽高
 */
val Context.screenWidth
    get() = resources.displayMetrics.widthPixels
val Context.screenHeight
    get() = resources.displayMetrics.heightPixels
val View.screenWidth
    get() = resources.displayMetrics.widthPixels
val View.screenHeight
    get() = resources.displayMetrics.heightPixels

/**
 * Int（视为dp）转px
 */
val Int.px
    get() = pxF.toInt()

/**
 * Int（视为dp）转px
 */
val Int.pxF
    get() = TypedValue.applyDimension(
        TypedValue.COMPLEX_UNIT_DIP,
        toFloat(),
        Resources.getSystem().displayMetrics
    )

val Float.px
    get() = pxF.toInt()

val Float.pxF
    get() = TypedValue.applyDimension(
        TypedValue.COMPLEX_UNIT_DIP,
        this,
        Resources.getSystem().displayMetrics
    )

val Int.fontSize
    get() = fontSizeF.toInt()

val Int.fontSizeF
    get() = TypedValue.applyDimension(
        TypedValue.COMPLEX_UNIT_SP,
        toFloat(),
        Resources.getSystem().displayMetrics
    )

fun Context.dp2px(dp: Int): Int {
    val density = resources.displayMetrics.density
    return (dp * density + 0.5F).toInt()
}

fun Context.px2dp(px: Int): Int {
    val density = resources.displayMetrics.density
    return (px / density + 0.5F).toInt()
}

fun Context.dp2pxF(dp: Int): Float {
    val density = resources.displayMetrics.density
    return dp * density
}

fun Context.px2dpF(px: Int): Float {
    val density = resources.displayMetrics.density
    return px / density
}

fun View.dp2px(dp: Int): Int {
    val density = resources.displayMetrics.density
    return (dp * density + 0.5F).toInt()
}

fun View.px2dp(px: Int): Int {
    val density = resources.displayMetrics.density
    return (px / density + 0.5F).toInt()
}

fun View.dp2pxF(dp: Int): Float {
    val density = resources.displayMetrics.density
    return dp * density
}

fun View.px2dpF(px: Int): Float {
    val density = resources.displayMetrics.density
    return px / density
}

fun <T> T?.notNullUnit(
    notNull: (t: T) -> Any,
    isNull: () -> Any
): Any {
    return if (this != null) {
        notNull(this)
    } else {
        isNull()
    }
}

fun <T> T?.notNull(
    notNull: (t: T) -> T,
    isNull: () -> T
): T {
    return if (this != null) {
        notNull(this)
    } else {
        isNull()
    }
}

fun Long.toDate(): Date {
    return Date(this)
}